package com.itheima;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.junit.jupiter.api.Test;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class jwtText {

    @Test
    public void textGen(){
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", "1");
        claims.put("username", "张三");
        String token = JWT.create()
                .withClaim("user", claims) // 挂载数据
                .withExpiresAt(new Date(System.currentTimeMillis() + 1000*60*60*12)) // 过期时间
                .sign(Algorithm.HMAC256("itheima")); // 加密算法
        System.out.println(token);
    }
    @Test
    public void testParse(){
        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9" +
                ".eyJleHAiOjE3NTk5NjkzNTEsInVzZXIiOnsiaWQiOiIxIiwidXNlcm5hbWUiOiLlvKDkuIkifX0" +
                ".zTpB0ZgatHeZkZzlc0ujrA5F9bTMUVpV9aJjdO47Plc";
        // 申请一个jwt验证器，build生成，用来解密
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("itheima")).build();
        // 验证token，生成一个解析后的jwt对象
        DecodedJWT decodedJWT =  jwtVerifier.verify(token);

        Map<String, Claim> claims = decodedJWT.getClaims();
        System.out.println(claims.get("user"));

    }
}
